package linc.cool.helloworld;

import com.rabbitmq.client.*;
import linc.cool.utils.RabbitConstant;
import linc.cool.utils.RabbitUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author yqlin
 * @date 2022/3/3 5:07 上午
 * @description
 */
@Slf4j
public class Consumer {
    public static void main(String[] args) throws IOException {
        // 获取TCP长连接
        Connection connection = RabbitUtils.getConnection();
        // 创建通信通道,相当于TCP中的虚拟连接
        Channel channel = connection.createChannel();
        channel.queueDeclare(RabbitConstant.QUEUE_HELLO_WORLD, false, false, false, null);
        channel.basicConsume(RabbitConstant.QUEUE_HELLO_WORLD, false, new MyConsumer(channel));
    }

    private static class MyConsumer extends DefaultConsumer {
        private final Channel channel;

        public MyConsumer(Channel channel) {
            super(channel);
            this.channel = channel;
        }

        @Override
        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            String message = new String(body);
            log.info("接收到的信息:{}", message);
            channel.basicAck(envelope.getDeliveryTag(), false);
        }
    }
}
